// electron/repository/CommandRepository.ts
import execa = require('execa');
import path from 'node:path';
import GlobalConstant from '../core/GlobalConstant';
import { PathFinder } from '../utils/path_manager';

class CommandRepository {
  async runCommand(command: string, args: string[]): Promise<string> {
    try {
      const { stdout, stderr } = await execa(command, args);
      return stderr || stdout;
    } catch (error) {
      return `命令执行失败: ${error instanceof Error ? error.message : String(error)}`;
    }
  }

  async runCommandWithStream(
    command: string,
    args: string[],
    onData: (msg: string) => void,
    onError?: (error: any) => void,
  ): Promise<string> {
    try {
      let subprocess;

      if (GlobalConstant.USE_EXTERNAL_SDK) {
        subprocess = execa(command, args, {
          stdio: ['ignore', 'pipe', 'pipe'],
        });
      } else {
        const isWindows = process.platform === 'win32';
        const binPath = path.join(
          PathFinder.VENV_PATH,
          isWindows ? 'Scripts' : 'bin',
        );

        subprocess = execa(command, args, {
          stdio: ['ignore', 'pipe', 'pipe'],
          env: {
            ...process.env,
            PATH: `${binPath}${path.delimiter}${process.env.PATH}`,
          },
        });
      }

      subprocess.stdout?.on('data', (data: Buffer) => onData(data.toString()));
      subprocess.stderr?.on('data', (data: Buffer) => onData(data.toString()));

      await subprocess;
      return '';
    } catch (error) {
      onError?.(error);
      return '';
    }
  }
}

export default new CommandRepository();
